using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using HWGames.Bundles.Internal.Editor;
using GoogleMobileAds.Editor;
using UnityEditor;
using UnityEngine;

namespace HWGames.Bundles.Internal {
    public class GoogleMobileAdsPreBuild : IPreprocessBuildWithReport {
        public int callbackOrder => 1;

        public void OnPreprocessBuild(BuildReport report) {
            CheckAndUpdateAdmobSettings(SDKBundleSettings.Load());
        }

        public static void CheckAndUpdateAdmobSettings(SDKBundleSettings settings) {
#if UNITY_ANDROID
            if (!CheckAdmobSettings(settings.enableBanner, settings.androidAdmobAppID, settings.androidRewardAdUnitID, settings.androidInterstitialAdUnitID, settings.androidBannerAdUnitID)) {
                BuildErrorWindow.LogBuildError(BuildErrorConfig.ErrorID.NoAdmobAndroidToken);
                return;
            }
            if ((int)PlayerSettings.Android.minSdkVersion < 21) {
                BuildErrorWindow.LogBuildError(BuildErrorConfig.ErrorID.API_LEVEL);
                return;
            }
            if ((int)PlayerSettings.Android.targetSdkVersion < 34) {
                BuildErrorWindow.LogBuildError(BuildErrorConfig.ErrorID.TARGET_API_LEVEL);
                return;
            }
#elif UNITY_IOS
            if (!CheckAdmobSettings(settings.enableIOSBanner, settings.iOSAdmobAppID, settings.iOSRewardAdUnitID, settings.iOSInterstitialAdUnitID, settings.iOSBannerAdUnitID)) {
                BuildErrorWindow.LogBuildError(BuildErrorConfig.ErrorID.NoAdmobiOSToken);
                return;
            }
#endif
            GoogleMobileAdsSettings adsSettings = GoogleMobileAdsSettings.LoadInstance();
            adsSettings.GoogleMobileAdsAndroidAppId = settings.androidAdmobAppID;
            adsSettings.GoogleMobileAdsIOSAppId = settings.iOSAdmobAppID;
            EditorUtility.SetDirty(adsSettings);
            //AssetDatabase.SaveAssets();
            //GoogleMobileAdsSettings.Instance.WriteSettingsToFile();
        }

        private static bool CheckAdmobSettings(bool enableBanner, string admobID, string rewardID, string interID, string bannerID) {
            if (IsNotNull(admobID) || IsNotNull(rewardID) || IsNotNull(interID)) {
                return false;
            }
            if (enableBanner && IsNotNull(bannerID)) {
                return false;
            }
            return true;
        }

        private static bool IsNotNull(string key) {
            return string.IsNullOrEmpty(key);
        }
    }
}
